package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    /*
    * 用户下单
    * */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        // 目标：生成用户订单表、订单详情表数据

        // 1.根据ordersSubmitDTO里面的收获地址ID，获取地址对象AddressBook
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        // 安全校验，判断收货地址是否为空
        if(addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 2.获取登陆的用户ID
        Long userId = BaseContext.getCurrentId();

        // 3.根据用户ID，获取购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.find(userId);
        // 判断购物车是否为空
        if(shoppingCartList == null || shoppingCartList.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 4.封装订单表Orders的数据，插入到数据库
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setNumber(UUID.randomUUID().toString().replace("-",""));// 订单号
        orders.setStatus(Orders.PENDING_PAYMENT);// 订单状态 1待付款
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID); // 支付状态 1未支付
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName()
        + addressBook.getDistrictName() + addressBook.getDetail()); // 收货地址
        orders.setConsignee(addressBook.getConsignee()); // 收货人
        orderMapper.save(orders);
        // 5.封装订单详情表List<OrderDetail>数据，插入数据库
        // 购物车有多少条记录，订单详情表就应该生成多少条记录
        // 定义List集合
        ArrayList<OrderDetail> orderDetailList = new ArrayList<>();
        // 便利购物车List<ShoppingCart>集合对象，将每个购物车对象封装成OrderDetail对象，追加到List<OrderDetail>集合中
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            // 设计逻辑外键orderId
            orderDetail.setOrderId(orders.getId());
            // 追加到集合中
            orderDetailList.add(orderDetail);
        }
        // 最后将List<OrderDetail>批量插入到数据库
        orderDetailMapper.saveBatch(orderDetailList);

        // 7.清空购物车
        shoppingCartMapper.deleteByUserId(userId);

        // 6.封装OrderSubmitVO对象，返回给前端
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();


    }

    /*
    * 支付订单
    * */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 用户订单分页查询
     *
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult pageQuery(Integer page, Integer pageSize, Integer status) {
        //1.将查询条件封装到OrderPageQueryDTO中
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setPage(page);
        ordersPageQueryDTO.setPageSize(pageSize);
        ordersPageQueryDTO.setStatus(status);
        //封装当前用户id
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());

        //2.设置PageHelper分页的页码和每页大小
        PageHelper.startPage(page,pageSize);

        //3.执行查询的sql语句，返回Page<Orders>
        //分析：select * from orders where status=#{status}
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);

        //4.定义List<OrderVO>来封装当前页数据列表，OrderVO可以封装Orders和List<OrderDetail>数据
        List<OrderVO> orderVOList = new ArrayList<>();

        //5.获取Page<Orders>的getResult()当前页数据列表，遍历出每个Orders对象，根据orders.getId()获取List<OrderDetail>'
        orderVOList = ordersPage.getResult().stream().map(orders -> {
            OrderVO orderVO = new OrderVO();
            //6.将Orders和List<OrderDetail>封装到OrderVO中，最后将每个OrderVO添加到List<OrderVO>中
            //将orders封装给orderVO
            BeanUtils.copyProperties(orders,orderVO);
            //根据orders.getId()查询订单详情表列表数据
            List<OrderDetail> orderDetailList = orderDetailMapper.findByOrderId(orders.getId());
            //List<OrderDetail>封装给OrderVO
            orderVO.setOrderDetailList(orderDetailList);

            //返回
            return orderVO;
        }).collect(Collectors.toList());

        //7.封装PageResult对象(total,List<OrderVO>)
        return new PageResult(ordersPage.getTotal(),orderVOList);
    }

    @Autowired
    private WebSocketServer webSocketServer;
    /*
    * 用户催单
    * */
    @Override
    public void reminder(Long id) {
        // 1.根据订单id获取订单数据Orders
        Orders orders = orderMapper.getById(id);

        // 订单对象Orders为null,抛出异常
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 2.创建对象发送给商家端
        // 状态2 用户催单
        // 订单主键
        // content = "订单号："+orders.getNumber()
        Map<String, Object> map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());

        // 3.使用websocket发送
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));

    }
}
